<template>
  <div class="preview">
    <el-image :src="img" fit="contain"></el-image>
    <div class="img-info">

      <div class="info-item">
        <div class="info-name">文件链接：</div>
        <div class="info-cont">{{img}}</div>
      </div>
      <div class="info-item">
        <div class="info-name">文件尺寸：</div>
        <div class="info-cont">{{width}}x{{height}}</div>
      </div>
      <div class="info-item">
        <div class="info-name">文件类型：</div>
        <div class="info-cont">{{type}}</div>
      </div>
      <div class="info-item">
        <div class="info-name">文件大小：</div>
        <div class="info-cont">{{size}}kb</div>
      </div>
      <div class="info-item">
        <div class="info-name">下载文件：</div>
        <div class="info-cont">
          <el-button type="primary" plain size="mini" @click="downLoad">下载</el-button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import axios from "axios";
/*
  案例
  * imgReady(this.img,function(){
      console.log("this",this.width,this.height)
    })
  * */
const imgReady = (function () {
  const list = []; let intervalId = null;
  // 用来执行队列
  const stop = function () {
    // 停止所有定时器队列
    clearInterval(intervalId);
    intervalId = null;
  };
  const tick = function () {
    for (let i = 0; i < list.length; i += 1) {
      list[i].end ? list.splice(i -= 1, 1) : list[i]();
    }
    !list.length && stop();
  };
  return function (url, ready, load, error) {
    let onready; let newWidth; let newHeight;
    let img = new Image();
    img.src = url;
    // 如果图片被缓存，则直接返回缓存数据
    if (img.complete) {
      ready.call(img);
      load && load.call(img);
      return;
    }
    const width = img.width;
    const height = img.height;
    // 加载错误后的事件
    img.onerror = function () {
      error && error.call(img);
      onready.end = true;
      img = img.onload = img.onerror = null;
    };
    // 图片尺寸就绪
    onready = function () {
      newWidth = img.width;
      newHeight = img.height;
      if (newWidth !== width || newHeight !== height || newWidth * newHeight > 1024) {
        // 如果图片已经在其他地方加载可使用面积检测
        ready.call(img);
        onready.end = true;
      }
    };
    onready();
    // 完全加载完毕的事件
    img.onload = function () {
      // onload在定时器时间差范围内可能比onready快
      // 这里进行检查并保证onready优先执行
      !onready.end && onready();
      load && load.call(img);
      // IE gif动画会循环执行onload，置空onload即可
      img = img.onload = img.onerror = null;
    };
    // 加入队列中定期执行
    if (!onready.end) {
      list.push(onready);
      // 无论何时只允许出现一个定时器，减少浏览器性能损耗
      if (intervalId === null) intervalId = setInterval(tick, 40);
    }
  };
}());
export default {
  name: "PreviewImg",
  data() {
    return {
      img: "",
      width: 0,
      height: 0,
      size: 0,
      type: ""
    }
  },
  created() {
    this.getImgInfo()
  },
  methods: {
    getImgInfo() {
      const _this = this;
      if (this.$route.query && this.$route.query.file) {
        _this.img = _this.$route.query.file;
        axios.get(this.img).then((e) => {
          _this.type = e.headers["content-type"];
          _this.size = (parseInt(e.headers["content-length"], 10) / 1024).toFixed(2);
          const typeList = ["image/png", "image/jpg", "image/jpeg", "image/gif"];
          if (typeList.findIndex((v) => _this.type === v) > -1) {
            imgReady(_this.img, function () {
              _this.width = this.width;
              _this.height = this.height;
            });
          }
        })
      }
    },
    downloadIamge(imgsrc, name) { // 下载图片地址和图片名
      const image = new Image();
      // 解决跨域 Canvas 污染问题
      image.setAttribute("crossOrigin", "anonymous");
      image.onload = function () {
        const canvas = document.createElement("canvas");
        canvas.width = image.width;
        canvas.height = image.height;
        const context = canvas.getContext("2d");
        context.drawImage(image, 0, 0, image.width, image.height);
        const url = canvas.toDataURL("image/png"); // 得到图片的base64编码数据
        const a = document.createElement("a"); // 生成一个a元素
        const event = new MouseEvent("click"); // 创建一个单击事件
        a.download = name || "神笔马良"; // 设置图片名称
        a.href = url; // 将生成的URL设置为a.href属性
        a.dispatchEvent(event); // 触发a的单击事件
      };
      image.src = imgsrc;
    },
    downLoad() {
      const f = this.img.lastIndexOf("/");
      const e = this.img.lastIndexOf(".");
      const name = this.img.substring(f + 1, e);
      this.downloadIamge(this.img, `神笔马良-${name}`);
    }
  }
}
</script>

<style lang="scss" scoped>
  .preview {
    position: relative;
    width: 100%;
    height: 100%;
  }

  .img-info {
    position: fixed;
    bottom: 20px;
    left: 20px;
    width: 400px;
    min-height: 160px;
    padding: 10px;
    box-shadow: 0 0 8px 2px rgba(0, 0, 0, 0.5);
    background: rgba(255, 255, 255, 0.3);
    -webkit-border-radius: 6px;
    -moz-border-radius: 6px;
    border-radius: 6px;
  }

  .info-item {
    width: 100%;
    display: flex;
    align-items: center;
    min-height: 40px;

    .info-name {
      font-size: 14px;
      color: $primary;
    }

    .info-cont {
      flex: 1;
      font-size: 14px;
      color: $primary;
      word-break: break-all;
      margin-bottom: 10px;

      &:last-child {
        margin-bottom: 0;
      }
    }
  }
</style>
